<?php
require_once APPLICATION_PATH . '/controllers/LoginController.php';

/**
 * 客户（卖主）控制器
 * @author Administrator
 *
 */
class CustomerController extends LoginController
{

    public function init()
    {
        parent::init();
    }

    /**
     * 列表
     * @see LoginController::indexAction()
     */
    public function indexAction()
    {
        if($this->getRequest()->isPost()){
        	//获取数据
        	$customerM = new Application_Model_DbTable_Customer();
        	$pageM = $this->_helper->Flexgp();
        	
        	$where = " 1=1 ";
        	$paramS= $this->getRequest()->getParams();
        	$paramA= array("user","region","type","trade","customer_degree");
        	
        	//待开发客户，还没有任何跟进状态的客户
        	if($this->getRequest()->getParam("menu_press_radio") == "0"){
		    	$hl2 = $customerM->getItemsHasMsg();
		    	$hasML = implode(",", $hl2);
		    	$where .= " AND `id` NOT IN ({$hasML})";
        	}
        	//跟进中
        	if($this->getRequest()->getParam("menu_press_radio") == "1"){
		    	$hl2 = $customerM->getItemsDoingMsg();
		    	$hasML = implode(",", $hl2);
		    	$where .= " AND `id` IN ({$hasML})";
        	}
        	//有客户报价
        	if($this->getRequest()->getParam("menu_press_radio") == "2"){
		    	$hl2 = $customerM->getItemsHasQuote();
		    	$hasML = implode(",", $hl2);
		    	$where .= " AND `id` IN ({$hasML})";
        	}
        	
        	foreach ($paramA as $p){
        		$where .= empty($paramS[$p])?"":" AND `{$p}`={$paramS[$p]} ";
        	}
        	
			$data = $customerM->jqfetchAll($pageM,$where);
			
			$enumDataM = new Application_Model_DbTable_Enumdata();
			$regionKV = $enumDataM->setName("region")->getKvIdName();
			$tradeKV  = $enumDataM->setName("trade")->getKvIdName();
			$degreeKV = $enumDataM->setName("customer_degree")->getKvIdName();
			 	
	    	$userM    = new Application_Model_DbTable_User();
	    	$userKV   = $userM->getKVnameid();
	    	
        	$rdata= $data["data"];
			foreach ($rdata as &$d){
				$d["region"] 			= empty($regionKV[$d["region"]])?"":$regionKV[$d["region"]];
				$d["trade"] 			= empty($tradeKV[$d["trade"]])?"":$tradeKV[$d["trade"]];
				$d["customer_degree"] 	= empty($degreeKV[$d["customer_degree"]])?"":$degreeKV[$d["customer_degree"]];
				$d["create_user"] 		= empty($userKV[$d["create_user"]])?"":$userKV[$d["create_user"]];
				$d["user"]				= empty($userKV[$d["user"]])?"":$userKV[$d["user"]];
				$d["create_time"] 		= date("Y-m-d H:i:s",$d["create_time"]);
			}
			
			$data = $this->view->jqflexgrid($data,"id");
		    $this->_helper->json($data); 
        }else{
        	//获取页面
        	$userM = new Application_Model_DbTable_User();
        	$userL = $userM->fetchAll();
        	$this->view->user = $userL;
        	
        	$countryM = new Application_Model_DbTable_Country();
        	$countryL = $countryM->fetchAll();
        	$this->view->country = $countryL;
        	
        	$tradeM   = new Application_Model_DbTable_Enumdata("trade");
        	$tradeL   = $tradeM->fetchAll();
        	$this->view->trade = $tradeL;
        	
        	$customer_degreeM   = new Application_Model_DbTable_Enumdata("customer_degree");
        	$customer_degreeL   = $customer_degreeM->fetchAll();
        	$this->view->degree = $customer_degreeL;
        	
        	
    		$this->view->title = "客户列表";
        }
    }

    /**
     * 添加
     * @see LoginController::indexAction()
     */
    public function addAction()
    {
    	$formM = new Application_Form_Base("customer");
        
        $enumM = new Application_Model_DbTable_Enumdata();
    	$enumM->setMultiOptionAll($formM);
    	if($this->getRequest()->isPost()){
        	//提交数据
        	//json返回的数据
        	$reData = array(
        		"status" => 0,
        		"msg"	 => "失败。"
        	);
        	$data = $this->getRequest()->getParams();
        	if($formM->isValid($data)){
        		$userM = new Application_Model_DbTable_Customer();
        		$data  = $formM->getValues(); 
        		//$data["id"] = $data["userid"];unset($data["userid"]);
        		$data['create_user'] = $this->_user_id;   //创建人id
	        	$data['create_time'] = time();                           //创建时间
	        	try {
		        	$result = $userM->insert($data);
		        	$reData["status"]=1;
		        	$reData["msg"]="成功！";
		        	Application_Service_Msg::write(
		        		"{$this->_user_name}添加客户：{$data["name"]}",
		        		Application_Model_Msg::TYPE_USERDO_LOG
		        	);
	        	}catch (Exception $e){
        			$reData["form"] = $formM->render();
	        		$reData["msg"]="数据库错误！" . $e->getMessage();
	        	}
        	}else{
        		$reData["msg"]="表单填写有误！";
        		$reData["form"] = $formM->render();
        	}
        	$this->_helper->json($reData);
        }else{
        	//获取表单
    		$this->view->form = $formM;
        }
        $this->_helper->layout()->disableLayout();
        $this->renderScript("zendform.phtml");
    }
    
    /**
     * 编辑
     * @see LoginController::indexAction()
     */
    public function editAction()
    {
    	$id = intval($this->getRequest()->getParam("id",0));
    	$formM = new Application_Form_Base("customer");
    	$userM = new Application_Model_DbTable_Customer();
        $formM->setAction($this->view->pagePath . "/customer/edit");
        
        $enumM = new Application_Model_DbTable_Enumdata();
    	$enumM->setMultiOptionAll($formM);
    	
    	if($this->getRequest()->isPost()){
        	//提交数据
        	$reData = array(
        		"status" => 0,
        		"msg"	 => "失败。"
        	);
        	$data = $this->getRequest()->getParams();
        	if($formM->isValid($data)){
        		
        		$data  = $formM->getValues(); 
        		unset($data["userid"]);
	        	try {
		        	$result = $userM->update($data, " `id` = {$id} ");
		        	$reData["status"]=1;
		        	$reData["msg"]="成功！";
		        	Application_Service_Msg::write(
		        		"{$this->_user_name}修改客户：{$data["name"]}",
		        		Application_Model_Msg::TYPE_USERDO_LOG
		        	);
	        	}catch (Exception $e){
        			$reData["form"] = $formM->render();
	        		$reData["msg"]="数据库错误！" . $e->getMessage();
	        	}
        	}else{
        		$reData["msg"]="表单填写有误！";
        		$reData["form"] = $formM->render();
        	}
        	$this->_helper->json($reData);
        }else{
        	//获取表单
        	$data = $userM->fetchRow(" `id` = {$id} ");
        	if($data){
        		$formM->setDefaults($data->toArray());
        	}
    		$this->view->form = $formM;
        }
        $this->_helper->layout()->disableLayout();
        $this->renderScript("zendform.phtml");
    }
    
	/**
	 * 删除
	 */
	public function delAction()
	{
		$reData = array(
			"status" => 0,
			"msg"    => "参数错误"
		);	    
    	$id = (array)$this->getRequest()->getParam('id');
    	if($id){
			$userM = new Application_Model_DbTable_Customer();
			$where = $userM->getAdapter()->quoteInto('`id` IN(?)', $id);
    		if($result = $result = $userM->delete($where)){
    			$reData = array(
					"status" => 1,
    		 		"msg"    => "成功删除{$result}条数据！"
    		 	);
    		 	$id = implode(",",$id);
    		 	Application_Service_Msg::write(
	        		"{$this->_user_name} 删除客户：{$id}",
	        		Application_Model_Msg::TYPE_USERDO_LOG
	        	);
    		 }
	    }else{
	        	
	    }
	    $this->_helper->json($reData);
   }

	/**
     * 设置负责人
     */
    public function setuserAction()
    {
    	$id	   = intval($this->getRequest()->getParam("id",0));
    	$formM = new Application_Form_Base("customer_setuser");
    	$formM->setAction($this->view->pagePath . "/customer/setuser");
    	$userM = new Application_Model_DbTable_User();
    	$userL = $userM->fetchAll(" `type` <> 0 ");
    	$userS = array();
    	foreach ($userL as $userI){
    		$userS[$userI->id] = $userI->showname;
    	}
    	$userList = $formM->getElement("user");
    	$userList->setMultiOptions($userS);
    	
    	if($this->getRequest()->isPost()){
	    	$user 	= intval($this->getRequest()->getParam("user",0));
	    	$note 	= $this->getRequest()->getParam("note",0);
	    	
	    	$formM->isValid($this->getRequest()->getPost());
	    	
	    	$redata = array(
	    		"status" => 0,
	    		"msg"	 => "错误",
	    		"form"	 => $formM->render()
	    	);
	    	
	    	if($this->_user->type != 0){
	    		$redata["msg"] = "sorry，您没有此权限";
	    		$this->_helper->json($redata);
	    	}
	    	
	    	if($id != 0){    		
	        	$customerM = new Application_Model_DbTable_Customer();
	    		$data = array(
	    			"user" => $user
	    		);
	    		try{
		    		if($customerM->update($data, " `id` = {$id} ")){
		    			$redata["status"] = 1;
		    			$redata["msg"] = "成功";
		    			
		    			$msg = $customerM->fetchRow(" `id` = {$id} ");
						$msg = $msg["name"];
		    			Application_Service_Msg::write(
			        		"{$this->_user_name} 分配给你一位客户：{$msg} ，注意事项为：{$note}",
			        		Application_Model_Msg::TYPE_MSG,
			        		$this->_user_id,
			        		$user
			        	);
		    		}else{
		    			$redata["msg"] = "修改失败！";
		    		}
	    		}catch (Exception $e){
	    			$redata["msg"] = "数据库错误 ： " . $e->getMessage();
	    		}
	    	}else {
	    		$redata["msg"] = "参数错误！";
	    	}
	    	$this->_helper->json($redata);
    	}else{    		
    		$mailId   = $formM->getElement("id");
    		$mailId->setValue($id);	
    		$this->view->form = $formM;
    		
	        $this->_helper->layout()->disableLayout();
	        $this->renderScript("zendform.phtml");
        }
    }
	
	/**
	 * 获取用户详细信息及代理人信息
	 */
	public function getiteminfoAction()
	{
		$id = intval($this->getRequest()->getParam("id"));
		$customerM = new Application_Model_DbTable_Customer();
		$custAgenM = new Application_Model_DbTable_custagent();
		$msgM	   = new Application_Model_DbTable_Msg();
		
		$customerV = $customerM->fetchRow(" `id` = {$id} ");
		$customerV = $customerV?$customerV->toArray():$customerV;
		$custAgenV = $custAgenM->fetchAll(" `customer` = {$id}");
		$msgV	   = $msgM->getListByType(Application_Model_Msg::TYPE_ALARM, 20);
		
		$formM = new Application_Form_Base("customer");
		$enumM = new Application_Model_DbTable_Enumdata();
    	$enumM->setMultiOptionAll($formM);
		$formM->isValid($customerV);
    	
		$elemS = $formM->getElements();
		foreach($elemS as $e){
			$formM->getElement($e->getName())->setAttrib("disabled", "disabled")->setAttrib("onClick", "return false;");
		}
		
		$this->view->customid 	 = $id;
		$this->view->custom 	 = $formM;
		$this->view->customAgent = $custAgenV->toArray();
		$this->view->msg 		 = $msgV;
		
		$this->_helper->layout()->disableLayout();
	}
}

